/**
 * 
 */
package com.fsharemobile.client;

import java.net.URL;
import java.util.List;

import org.json.JSONObject;

import com.fsharemobile.client.APICallTask.OnAPICallCompleted;


/**
 * @author RAD-Dungtm9
 * 
 */
public class UserProxy {

	public UserProxy(FClient fclient) {
		super();
		this.fclient = fclient;
	}

	public static final String loginUri = "http://fshare.rad.fpt.net/api/user/login";

	public void login(String userid, String password,
			final OnLoginCompleted callback) throws Exception {
		// build post data
		StringBuffer sbPostData = new StringBuffer("");
		sbPostData.append("{");
		sbPostData.append(String.format("\"app_key\":\"%s\"", FClient.APP_KEY));
		sbPostData.append(String.format(",\"user_email\":\"%s\"", userid));
		sbPostData.append(String.format(",\"password\":\"%s\"", password));
		sbPostData.append("}");
		HttpRequest request = new HttpRequest();
		request.setUrl(new URL(loginUri));
		request.setBody(sbPostData.toString());
		// call api
		new APICallTask(fclient.getHttputil(), new OnAPICallCompleted() {
			@Override
			public void onAPICallCompleted(HttpResponse response) {
				// parse result (json)
				int errCode = 0;
				JSONObject jso = null;
				try {
					// check http code
					errCode = response.getHttpCode();
					if (response.getHttpCode() != 200) {
						callback.onLoginCompleted(errCode);
						return;
					}
					jso = new JSONObject(response.getBodyAsString());
					errCode = Integer.parseInt(jso.getString("code"));
					if (errCode != 200) {
						callback.onLoginCompleted(errCode);
						return;
					}
					errCode = 0;
					// set token, session_id to fclient
					fclient.setToken(jso.getString("token"));
					fclient.setSessionid(jso.getString("session_id"));
					// save cookie
					List<String> cookies = fclient.getCookies();

					if (response.getHeaderFields().containsKey("Set-Cookie")) {
						List<String> res_cookie = response.getHeaderFields()
								.get("Set-Cookie");
						cookies.add(res_cookie.get(res_cookie.size() - 1));
					}
				} catch (Exception jex) {
					System.out.println(jex.toString());
					errCode = 2;
				}
				callback.onLoginCompleted(errCode);
				// save cookie from response

			}
		}).execute(request);
	}

	public interface OnGetListCompleted {
		void onGetListCompleted(String result);
	}

	public interface OnLoginCompleted {
		void onLoginCompleted(int errCode);
	}

	/**
	 * @return the fclient
	 */
	public FClient getFclient() {
		return fclient;
	}

	private FClient fclient;

}
